package api

import (
	"encoding/json"
	"gitee.com/godY/daminghu-cli-server/buildcmd"
	"gitee.com/godY/daminghu-cli-server/cfg"
	"gitee.com/godY/daminghu-cli-server/common"
	"gitee.com/godY/daminghu-cli-server/email"
	"gitee.com/godY/daminghu-cli-server/msg"
	"github.com/astaxie/beego/logs"
	_ "github.com/go-sql-driver/mysql"
	"io"
	"io/ioutil"
	"os"
)

type CREATE_CONTROLLER struct {
	baseController
}

//curl -X POST "http://localhost:12345/api/user/login" -H "accept: application/json"  -d "username=user06&password=1112221"
func (this *CREATE_CONTROLLER) CreateAll() {

	//if err = json.Unmarshal(this.Ctx.Input.RequestBody, &req); err == nil {
	//
	//	ioutil.WriteFile("", this.Ctx.Input.RequestBody, os.ModePerm)
	//} else {
	//	panic(err)
	//}

	//var req msg.CreateReq
	var err error
	var now = common.GetNowTimeYYYYMMDDhhmmss()
	//save json file
	datafilename := common.TEMPPATH + now + ".data.json"
	datafile, _, err := this.GetFile("data")
	//logs.Info(datafile)
	//logs.Info(header)
	if err != nil {
		this.ReturnError(err)
	}
	dataf, err := os.OpenFile(datafilename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
	if err != nil {
		this.ReturnError(err)
	}
	_, err = io.Copy(dataf, datafile)
	if err != nil {
		this.ReturnError(err)
	}

	//dumpfilename := common.TEMPPATH + now + ".dump.sql"
	//dumpfile, _, err := this.GetFile("sql")
	////logs.Info(dumpfile)
	////logs.Info(header)
	//if err != nil {
	//	this.ReturnError(err)
	//}
	//dumpf, err := os.OpenFile(dumpfilename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
	//if err != nil {
	//	this.ReturnError(err)
	//}
	//_, err = io.Copy(dumpf, dumpfile)
	//if err != nil {
	//	this.ReturnError(err)
	//}

	//save cfg file
	cfgfilename := common.TEMPPATH + now + ".cfg.json"
	cfgfile, _, err := this.GetFile("cfg")
	if err != nil {
		this.ReturnError(err)
	}
	cfgf, err := os.OpenFile(cfgfilename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.ModePerm)
	if err != nil {
		this.ReturnError(err)
	}
	_, err = io.Copy(cfgf, cfgfile)
	if err != nil {
		this.ReturnError(err)
	}

	bytes, err := ioutil.ReadFile(cfgfilename)
	if err != nil {
		this.ReturnError(err)
	}
	cfgObj := cfg.Config{}
	err = json.Unmarshal(bytes, &cfgObj)
	if err != nil {
		this.ReturnError(err)
	}

	//save old projectname
	//oldProjectName := cfgObj.ProjectName
	//update local dist path
	cfgObj.DistPath = common.DISTPATH + now + "/"
	//update loacl projecturi
	cfgObj.PrefixProjectUri = "gitee.com/godY"
	cfgObj.ProjectName = cfgObj.ProjectName + "-" + now

	cfgObjBytes, err := json.Marshal(cfgObj)
	cfgNewFileName := common.TEMPPATH + now + ".cfg.new.json"
	err = ioutil.WriteFile(cfgNewFileName, cfgObjBytes, os.ModePerm)

	//db file
	dbfilename := common.TEMPPATH + now + ".db.sql"
	dbfile, _, err := this.GetFile("sql")
	if err != nil {
		this.ReturnError(err)
	} else {
		dbf, err := os.OpenFile(dbfilename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.ModePerm)
		if err != nil {
			this.ReturnError(err)
		} else {
			io.Copy(dbf, dbfile)
		}
	}

	var build = this.GetString("build")
	var pemail = this.GetString("email")
	//set all default
	build = "all"

	if pemail != "" {
		logs.Info("Async Task Mode")
		//btask := task.BuildTask{}
		//btask.CfgObj = &cfgObj
		//btask.Build = build
		//btask.Email = pemail
		//btask.ReceivedCfgpath = cfgNewFileName
		//btask.ReceivedJsondatapath = datafilename
		//task.AddBuildTask(btask)

		go func() {
			logs.Info("Start Async Task......")
			buildcmd.RunDaminghuCliCmd(build, cfgNewFileName, datafilename)

			token := make(chan int, 2)
			go func() {
				buildcmd.BuildServer(cfgObj.GetServerProjcetPath(), cfgObj.GetServerProjcetName())
				token <- 1
			}()
			go func() {
				buildcmd.BuildWeb(cfgObj.GetWebProjcetPath(), cfgObj.GetWebProjcetName())
				token <- 1
			}()

			<-token
			<-token

			files := []string{
				common.DOWNLOAD_FILEPATH + cfgObj.GetWebProjcetName() + ".zip",
				common.EASYWEB_FILEPATH + "easyweb.zip"}

			err := email.SendEmail(pemail, files)
			if err != nil {
				logs.Error(err)
			}

			err = email.SendEmail(pemail, []string{common.DOWNLOAD_FILEPATH + cfgObj.GetServerProjcetName() + ".zip"})
			if err != nil {
				logs.Error(err)
			}
			logs.Info("End Async Task!")
		}()

		res := msg.ResponseBuilder().OptR().SuccessResponse().Build()
		res.Result = 1
		res.Message = "######The project file will send to ***" + pemail + "*** about 2-3min,please check it######."
		res.Token = this.CreateToken()
		this.Data["json"] = &res
		this.ServeJSON()
		this.StopRun()
	} else {
		logs.Info("Sync Method Mode")
		buildcmd.RunDaminghuCliCmd(build, cfgNewFileName, datafilename)

		token := make(chan int, 2)
		go func() {
			buildcmd.BuildServer(cfgObj.GetServerProjcetPath(), cfgObj.GetServerProjcetName())
			token <- 1
		}()
		go func() {
			buildcmd.BuildWeb(cfgObj.GetWebProjcetPath(), cfgObj.GetWebProjcetName())
			token <- 1
		}()

		<-token
		<-token

		resBody := msg.CreateResBody{}
		resBody.SvrZipUrl = common.DOWNLOAD_PRE_URL + cfgObj.GetServerProjcetName() + ".zip"
		resBody.WebZipUrl = common.DOWNLOAD_PRE_URL + cfgObj.GetWebProjcetName() + ".zip"
		res := msg.ResponseBuilder().OptR().SuccessResponse().Build()
		res.Body = resBody
		res.Message = "The project create complete,please check it."
		res.Token = this.CreateToken()
		this.Data["json"] = &res
		this.ServeJSON()
	}

}

func (this *CREATE_CONTROLLER) CreateServer() {

	var req msg.CreateReq
	var err error
	if err = json.Unmarshal(this.Ctx.Input.RequestBody, &req); err == nil {

	} else {
	}

	resBody := msg.CreateResBody{}
	resBody.SvrZipUrl = "https://gitee.com/godY/daminghu-cli/raw/master/download/server.zip"
	res := msg.ResponseBuilder().OptR().SuccessResponse().Build()
	res.Body = resBody
	res.Token = this.CreateToken()
	this.Data["json"] = &res
	this.ServeJSON()
}

func (this *CREATE_CONTROLLER) CreateWeb() {

	var req msg.CreateReq
	var err error
	if err = json.Unmarshal(this.Ctx.Input.RequestBody, &req); err == nil {

	} else {
	}

	resBody := msg.CreateResBody{}
	resBody.SvrZipUrl = "https://gitee.com/godY/daminghu-cli/raw/master/download/server.zip"
	res := msg.ResponseBuilder().OptR().SuccessResponse().Build()
	res.Body = resBody
	res.Token = this.CreateToken()
	this.Data["json"] = &res
	this.ServeJSON()
}

func (this *CREATE_CONTROLLER) Create() {

	this.Ctx.ResponseWriter.Write([]byte("Great! Bin!"))

}
